package tcp_proxy_router

import (
	"context"
	"fmt"
	"go_gateway/cmd"
	"go_gateway/reverse_proxy"
	"go_gateway/tcp_server"
	"os"

	"github.com/urfave/cli/v2"
)

func TcpServerRun(name, listen, host string) {
	router := NewTcpRouter()
	proxy := reverse_proxy.NewTcpReverseProxy(context.Background(), host)
	tcpHandler := NewTcpRouterHandler(func(trc *TcpRouterContext) tcp_server.TCPHandler {
		return proxy
	}, router)
	tcp_server.ListenAndServe(":"+listen, tcpHandler)
}

func Run(ctx *cli.Context) error {
	name := ctx.String("name")
	listen := ctx.String("listen")
	host := ctx.String("host")
	TcpServerRun(name, listen, host)
	return nil
}

func init() {
	command := &cli.Command{
		Name:  "tcp_proxy",
		Usage: fmt.Sprintf("%s tcp_proxy", os.Args[0]),
		Action: func(ctx *cli.Context) error {
			return Run(ctx)
		},
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:    "name",
				Aliases: []string{"n"},
				Value:   "tcp_proxy",
			},
			&cli.StringFlag{
				Name:    "listen",
				Aliases: []string{"l"},
				Value:   "8089",
			},
			&cli.StringFlag{
				Name:    "host",
				Aliases: []string{"ho"},
				Value:   "127.0.0.1:9002",
			},
		},
	}
	cmd.Register(command)
}
